package online.exam.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import online.exam.mapper.ClazzTypeMapper;
import online.exam.pojo.ClazzType;
import online.exam.service.ClazzTypeService;
import online.exam.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 王景煜
 */

@Service
public class ClazzTypeServiceImpl implements ClazzTypeService {

    @Autowired
    private ClazzTypeMapper clazzTypeMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PageUtils<ClazzType> queryAll(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<ClazzType> clazzTypeList = clazzTypeMapper.selectAll();
        PageInfo<?> clazzPageInfo = new PageInfo<>(clazzTypeList);
        PageUtils<ClazzType> utils = new PageUtils<>();
        utils.setPage(page);
        utils.setLimit(limit);
        utils.setCount(clazzPageInfo.getTotal());
        utils.setData(clazzTypeList);
        return utils;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ClazzType> queryAll() {
        return clazzTypeMapper.selectAll();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ClazzType queryByName(String name) {
        Example ctExample = new Example(ClazzType.class);
        Example.Criteria ctCriteria = ctExample.createCriteria();
        ctCriteria.andEqualTo("classType", name);
        return clazzTypeMapper.selectOneByExample(ctExample);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int addClassType(String className) {
        ClazzType type = new ClazzType();
        type.setId(IdUtil.simpleUUID());
        type.setClassType(className);
        type.setCreatedTime(new Date());
        int result = clazzTypeMapper.insert(type);
        return result > 0 ? HttpStatus.HTTP_OK : HttpStatus.HTTP_INTERNAL_ERROR;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int deleteClassType(String id) {
        if (id.contains(",")) {
            String[] ids = id.split("\",\"");
            List<String> idList = new ArrayList<>(Arrays.asList(ids));
            int clazzTypeResult = clazzTypeMapper.deleteMorePojo(idList);
            return ids.length == clazzTypeResult ? HttpStatus.HTTP_OK : HttpStatus.HTTP_INTERNAL_ERROR;
        }
        int clazzTypeResult = clazzTypeMapper.deletePojo(id);
        return clazzTypeResult > 0 ? HttpStatus.HTTP_OK : HttpStatus.HTTP_INTERNAL_ERROR;
    }

}
